// 微服务端到端测试专用配置
export const microservicesE2EConfig = {
  // 服务发现配置
  serviceDiscovery: {
    consul: {
      url: 'http://localhost:8500',
      healthCheck: '/v1/status/leader',
      services: '/v1/catalog/services'
    }
  },

  // 微服务健康检查配置
  healthChecks: {
    apiGateway: {
      url: 'http://localhost:8081/actuator/health',
      expectedStatus: 'UP',
      timeout: 30000
    },
    userService: {
      url: 'http://localhost:8082/actuator/health',
      expectedStatus: 'UP',
      timeout: 30000
    },
    courseService: {
      url: 'http://localhost:8083/actuator/health',
      expectedStatus: 'UP',
      timeout: 30000
    },
    exerciseService: {
      url: 'http://localhost:8084/actuator/health',
      expectedStatus: 'UP',
      timeout: 30000
    },
    progressService: {
      url: 'http://localhost:8085/actuator/health',
      expectedStatus: 'UP',
      timeout: 30000
    },
    mysql: {
      url: 'http://localhost:3306',
      timeout: 10000
    }
  },

  // 端到端测试场景配置
  e2eScenarios: {
    // 用户注册登录流程
    userAuthentication: {
      name: '用户认证端到端测试',
      steps: [
        '用户注册',
        '用户登录',
        '获取用户信息',
        '用户登出'
      ],
      expectedServices: ['userService', 'apiGateway']
    },

    // 课程管理完整流程
    courseManagement: {
      name: '课程管理端到端测试',
      steps: [
        '教师登录',
        '创建课程',
        '上传课程资料',
        '学生加入课程',
        '查看课程列表',
        '查看课程详情'
      ],
      expectedServices: ['userService', 'courseService', 'apiGateway']
    },

    // 练习管理完整流程
    exerciseManagement: {
      name: '练习管理端到端测试',
      steps: [
        '教师创建练习',
        '学生查看练习',
        '学生提交答案',
        '教师评分',
        '查看成绩'
      ],
      expectedServices: ['userService', 'exerciseService', 'apiGateway']
    },

    // 学习进度跟踪
    learningProgress: {
      name: '学习进度端到端测试',
      steps: [
        '学生登录',
        '查看学习记录',
        '更新学习进度',
        '查看统计数据'
      ],
      expectedServices: ['userService', 'progressService', 'apiGateway']
    },

    // 跨服务数据一致性测试
    dataConsistency: {
      name: '数据一致性端到端测试',
      steps: [
        '创建用户',
        '创建课程',
        '用户加入课程',
        '验证各服务数据一致性'
      ],
      expectedServices: ['userService', 'courseService', 'progressService', 'apiGateway']
    }
  },

  // 性能测试配置
  performance: {
    loadTest: {
      concurrentUsers: 10,
      duration: 60, // 秒
      rampUpTime: 10 // 秒
    },
    stressTest: {
      concurrentUsers: 50,
      duration: 120,
      rampUpTime: 20
    }
  },

  // 故障注入配置
  faultInjection: {
    networkLatency: {
      enabled: false,
      delay: 1000, // 毫秒
      probability: 0.1
    },
    serviceFailure: {
      enabled: false,
      targetService: 'courseService',
      failureRate: 0.05
    }
  }
}

// 微服务端到端测试工具类
export class MicroservicesE2ETestUtils {
  constructor() {
    this.config = microservicesE2EConfig
  }

  // 检查所有微服务健康状态
  async checkAllServicesHealth() {
    const healthResults = {}
    
    for (const [serviceName, config] of Object.entries(this.config.healthChecks)) {
      try {
        const response = await cy.request({
          method: 'GET',
          url: config.url,
          timeout: config.timeout,
          failOnStatusCode: false
        })
        
        healthResults[serviceName] = {
          status: response.status,
          healthy: response.status === 200,
          response: response.body
        }
      } catch (error) {
        healthResults[serviceName] = {
          status: 'ERROR',
          healthy: false,
          error: error.message
        }
      }
    }
    
    return healthResults
  }

  // 验证服务发现
  async verifyServiceDiscovery() {
    try {
      const response = await cy.request({
        method: 'GET',
        url: this.config.serviceDiscovery.consul.services,
        failOnStatusCode: false
      })
      
      if (response.status === 200) {
        const services = response.body
        return {
          success: true,
          services: Object.keys(services),
          consulHealthy: true
        }
      } else {
        return {
          success: false,
          consulHealthy: false,
          status: response.status
        }
      }
    } catch (error) {
      return {
        success: false,
        consulHealthy: false,
        error: error.message
      }
    }
  }

  // 跨服务数据一致性验证
  async verifyDataConsistency(userId, courseId) {
    const consistencyChecks = {}
    
    // 检查用户服务中的用户信息
    try {
      const userResponse = await cy.request({
        method: 'GET',
        url: `${this.config.healthChecks.userService.url.replace('/actuator/health', '')}/api/users/${userId}`,
        failOnStatusCode: false
      })
      consistencyChecks.userService = userResponse.status === 200
    } catch (error) {
      consistencyChecks.userService = false
    }

    // 检查课程服务中的课程信息
    try {
      const courseResponse = await cy.request({
        method: 'GET',
        url: `${this.config.healthChecks.courseService.url.replace('/actuator/health', '')}/api/courses/${courseId}`,
        failOnStatusCode: false
      })
      consistencyChecks.courseService = courseResponse.status === 200
    } catch (error) {
      consistencyChecks.courseService = false
    }

    // 检查进度服务中的学习记录
    try {
      const progressResponse = await cy.request({
        method: 'GET',
        url: `${this.config.healthChecks.progressService.url.replace('/actuator/health', '')}/api/progress/learning/${userId}/${courseId}`,
        failOnStatusCode: false
      })
      consistencyChecks.progressService = progressResponse.status === 200
    } catch (error) {
      consistencyChecks.progressService = false
    }

    return consistencyChecks
  }

  // 生成端到端测试报告
  generateE2EReport(testResults) {
    const report = {
      timestamp: new Date().toISOString(),
      summary: {
        totalTests: testResults.length,
        passed: testResults.filter(r => r.success).length,
        failed: testResults.filter(r => !r.success).length,
        successRate: 0
      },
      services: {},
      scenarios: {},
      recommendations: []
    }

    // 计算成功率
    report.summary.successRate = (report.summary.passed / report.summary.totalTests) * 100

    // 分析服务状态
    testResults.forEach(result => {
      if (result.serviceHealth) {
        Object.entries(result.serviceHealth).forEach(([service, health]) => {
          if (!report.services[service]) {
            report.services[service] = { healthy: 0, unhealthy: 0 }
          }
          if (health.healthy) {
            report.services[service].healthy++
          } else {
            report.services[service].unhealthy++
          }
        })
      }
    })

    // 生成建议
    if (report.summary.successRate < 90) {
      report.recommendations.push('端到端测试成功率较低，建议检查微服务间通信和依赖关系')
    }

    Object.entries(report.services).forEach(([service, stats]) => {
      if (stats.unhealthy > stats.healthy) {
        report.recommendations.push(`${service}服务健康状态不稳定，建议检查服务配置和依赖`)
      }
    })

    return report
  }
}

// 导出工具实例
export const microservicesE2EUtils = new MicroservicesE2ETestUtils()
